//
//  DiaryPhotoBrowseViewController.m
//  Growth
//
//  Created by Hobo.Chen on 7/13/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "DiaryPhotoBrowseViewController.h"
#import "WebRequest.h"
#import "WebConnetionArray.h"
#import "WebConnection.h"

static WebConnectionArray *browseAlbumList_connection = nil;
static WebConnectionArray *albumModify_connection = nil;    

static WebConnectionArray *oldDiaryAlbum_connetion = nil;
static WebConnectionArray *newDiaryAlbum_connetion = nil;


static BOOL isAnniversary = NO;

static int curIndex = 0;


static int oldPictureCount = 0;
static int newPictureCount = 0;

static NSString *maxTimePoint;
static NSString *minTimePoint;


static BOOL isLoadNew = false;
static BOOL isLoadOld = false;


@implementation DiaryPhotoBrowseViewController



@synthesize networkImages;

@synthesize imageURLArray;



#pragma mark - View lifecycle

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


-(id)initWithImages:(NSArray *)images  dateArray:(NSArray *)dates page:(int)page localImageNum:(int)localImageNum  isPersonalTimeline:(BOOL)_isPersonalTimeline{
    
    [super init];
    
    self.networkImages = [[NSMutableArray alloc]init];
    [self.networkImages addObjectsFromArray:images];
    
    if (dates != nil) {
        
         dateArray = [[NSMutableArray alloc]init];
        [dateArray addObjectsFromArray:dates];
    }
       
    oldPictureCount = 0;
    newPictureCount = 0;
    
    curPage = page;
    
    localImageCount = localImageNum;
    
    isAnniversary = YES;
    
    isPersonalTimeline = _isPersonalTimeline;
    
    return self;
    
    
}



//本地数据
- (id)initWithLocalImages:(NSArray *)images  page:(int)page{
    
    [super init];
    
    localImages  = [[NSMutableArray alloc]init];
    [localImages addObjectsFromArray:images];
    
    
    curPage = page;
    isLocalImage = YES;
    
    isAnniversary = NO;
    
    return self;
    
    
    
}


- (void)loadView {
    
	[super loadView];
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    [self loadBrowseView];
    
    if (albumMonthArray == nil) {
        albumMonthArray = [[NSMutableArray alloc]init];
    }

    
    if (isPersonalTimeline) {
        
        [self loadDiaryAlbum];
        
        //HPGrowingTextViewDelegate
        [self initGrowingTextView];
        if(self){
            [[NSNotificationCenter defaultCenter] addObserver:self 
                                                     selector:@selector(keyboardWillShow:) 
                                                         name:UIKeyboardWillShowNotification 
                                                       object:nil];
            
            [[NSNotificationCenter defaultCenter] addObserver:self 
                                                     selector:@selector(keyboardWillHide:) 
                                                         name:UIKeyboardWillHideNotification 
                                                       object:nil];		
        }
        

    }
    
     
}


#pragma mark -
#pragma mark Load View
- (void)loadBrowseView
{
    UIImage *captionIcon = [UIImage imageNamed:@"write_photo_iphone.png"];
    
    UIBarButtonItem *editCaptionButton = [[[UIBarButtonItem alloc] initWithImage:captionIcon style:UIBarButtonItemStylePlain target:self action:@selector(handleEditCaptionButtonTouch:)] autorelease];
    NSArray *rightBarItems = [NSArray arrayWithObjects:editCaptionButton, nil];
    
    
    UIImage *sendBtnBackground = [[UIImage imageNamed:@"topbuttonBG_iphone.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    UIImage *selectedSendBtnBackground = [[UIImage imageNamed:@"topbuttonBG1_iphone.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 40, 30);
    leftButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    [leftButton setTitle:@"设为封面" forState:UIControlStateNormal];
    leftButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [leftButton.titleLabel setTextColor:[UIColor whiteColor]];
    [leftButton addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
    [leftButton setBackgroundImage:selectedSendBtnBackground forState:UIControlStateSelected];
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    
    
    NSArray *leftBarItems = [NSArray arrayWithObjects:leftButtonItem, nil];
    
    
    //    browseGallery = [[FGalleryViewController alloc] initWithPhotoSource:self rightBarItems:rightBarItems leftBarItems:leftBarItems];
    //    [self.navigationController pushViewController:browseGallery animated:YES];
    //    [browseGallery release];
    
    
    //xiaoyan
    if (localImages == nil) {
        localImages = [[NSMutableArray alloc]init];
    }
    
    if (localImages.count>0) {
        
        CLog(@"local images %@", localImages);
        browseGallery = [[FGalleryViewController alloc] initWithPhotoSource:self ];
        [self.navigationController pushViewController:browseGallery animated:YES];
        [browseGallery release];
        
    }
    else{
        
        
        if (imageURLArray == nil) {
            
            imageURLArray = [[NSMutableArray alloc] init];
            
        }
        else{
            
            [imageURLArray removeAllObjects];
        }
        
        for (int i = 0;i<networkImages.count ; i++) {
            
            if ( curIndex < localImageCount ) { //本地图
                
                [imageURLArray addObject:[networkImages objectAtIndex:i]];
                
            }
            else{
                
                NSString *string=[NSString stringWithFormat:@"%@%@/%@/480x480",BASEURL,@"/commons/attachment/download",[networkImages objectAtIndex:i]];
                [imageURLArray addObject:string];
            }
            
            CLog(@"net image %@", [imageURLArray objectAtIndex:i]);
            
        }    
        
               
        if (isPersonalTimeline) {
            
            browseGallery = [[FGalleryViewController alloc] initDiaryPictureWithPhotoSource:self page:curPage rightBarItems:rightBarItems leftBarItems:leftBarItems isDiary:YES];
        }
        else{
            browseGallery = [[FGalleryViewController alloc]initWithPhotoSource:self];
            
        }
              
           [self.navigationController pushViewController:browseGallery animated:YES];
        
        [browseGallery release];
    }
    
    
}


#pragma mark -
#pragma mark HPGrowingTextViewDelegate

- (BOOL)growingTextView:(HPGrowingTextView *)growingTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    //当检测到有回车输入时即为点击了Done按钮，收起键盘
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder];
        
        [self resignTextView];
        
        return NO;
    }
    
    return YES;
}

- (BOOL)growingTextViewShouldReturn:(HPGrowingTextView *)growingTextView
{
    return YES;
}

- (void)initGrowingTextView{
    
    containerBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, CGRectGetHeight(self.view.frame))];
    
    CLog(@"browseGallery height %f", CGRectGetHeight(self.view.frame));
    
    [containerBgView setBackgroundColor:[UIColor colorWithRed:44.0 /255.0 green:136.0  /255.0 blue:35.0  /255.0 alpha:0.35]];
    
    UIButton *bgButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];
    [bgButton setBackgroundColor:[UIColor clearColor]];
    [bgButton addTarget:self action:@selector(cancelEditAction:) forControlEvents:UIControlEventTouchDown];
    [containerBgView addSubview:bgButton];
    
    
    containerView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(containerBgView.frame), 320, 50)];
    //
    containerView.backgroundColor = [UIColor redColor];
    
    
	textView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(10, 10, 233, 50)];
    textView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
    
	textView.minNumberOfLines = 1;
	textView.maxNumberOfLines = 6;
	textView.returnKeyType = UIReturnKeyGo; //just as an example
	textView.font = [UIFont systemFontOfSize:15.0f];
	textView.delegate = self;
    //textView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    textView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(50, 0, 5, 0);
    
    textView.backgroundColor = [UIColor whiteColor];
    textView.returnKeyType = UIReturnKeySend;
    
    // textView.text = @"test\n\ntest";
	// textView.animateHeightChange = NO; //turns off animation
    
    // [self.delegate addGrowingTextView:containerView];
    
	
    UIImage *rawEntryBackground = [UIImage imageNamed:@"MessageEntryInputField.png"];
    UIImage *entryBackground = [rawEntryBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *entryImageView = [[[UIImageView alloc] initWithImage:entryBackground] autorelease];
    //entryImageView.frame = CGRectMake(5, 0, 248, 40);
    
    entryImageView.frame = CGRectMake(10, 0, 233, 50);
    entryImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    UIImage *rawBackground = [UIImage imageNamed:@"MessageEntryBackground.png"];
    UIImage *background = [rawBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:background] autorelease];
    imageView.frame = CGRectMake(0, 0, containerView.frame.size.width, containerView.frame.size.height);
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    // view hierachy
    [containerView addSubview:imageView];
    [containerView addSubview:textView];
    [containerView addSubview:entryImageView];
    
    //发送评论
    UIImage *sendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    UIImage *selectedSendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    
	UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	doneBtn.frame = CGRectMake(containerView.frame.size.width - 69, 8, 63, 27);
    doneBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
	[doneBtn setTitle:@"完成" forState:UIControlStateNormal];
    
    [doneBtn setTitleShadowColor:[UIColor colorWithWhite:0 alpha:0.4] forState:UIControlStateNormal];
    doneBtn.titleLabel.shadowOffset = CGSizeMake (0.0, -1.0);
    doneBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    
    [doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	[doneBtn addTarget:self action:@selector(resignTextView) forControlEvents:UIControlEventTouchUpInside];
    [doneBtn setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
    [doneBtn setBackgroundImage:selectedSendBtnBackground forState:UIControlStateSelected];
	[containerView addSubview:doneBtn];
    
    containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    [containerBgView addSubview:containerView];
}

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);
    
	CGRect r = containerView.frame;
    r.size.height -= diff;
    r.origin.y += diff;
	containerView.frame = r;
}

//Code from Brett Schumann
-(void) keyboardWillShow:(NSNotification *)note{
    // get keyboard size and loctaion
	CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
	// get a rect for the textView frame
	CGRect containerFrame = containerView.frame;
    // containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);
    
    
    containerFrame.origin.y = CGRectGetHeight(containerBgView.frame) - (keyboardBounds.size.height + containerFrame.size.height) -43;
    
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	
	// set views with new info
	containerView.frame = containerFrame;
	
	// commit animations
	[UIView commitAnimations];
    
    //backGround button
    
    //backGoundButton.hidden = NO;
    
    
}

-(void) keyboardWillHide:(NSNotification *)note{
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
	
	// get a rect for the textView frame
	CGRect containerFrame = containerView.frame;
    containerFrame.origin.y = CGRectGetHeight(containerBgView.frame);
    
    // containerFrame.origin.y = 380;
	
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
	// set views with new info
	containerView.frame = containerFrame;
	
	// commit animations
	[UIView commitAnimations];
    
    //backGroundButton
    //backGoundButton.hidden = YES;
}


- (void)cancelEditAction:(id)sender
{
    [containerBgView removeFromSuperview];
}

-(void)resignTextView
{
    
    [browseGallery.view setUserInteractionEnabled:YES];
    //[self commitComment:textView.text ];
    CLog(@"new memo %@", textView.text) ;
    
    NSString *newMemo = textView.text;
    
    [containerBgView removeFromSuperview];
    
    NSInteger index = browseGallery._currentIndex;
    
    NSMutableDictionary *dict = [albumMonthArray objectAtIndex:index];
    
    NSString *currentMemo = [dict objectForKey:@"memo"];
    
    if (![currentMemo isMemberOfClass:[NSNull class]] && [currentMemo isEqualToString:newMemo]) {
        return;
    }
    
    [dict setObject:newMemo forKey:@"memo"];
    
    [browseGallery setCaptionWith:newMemo];
    
    CLog(@"EditCaption ");
    
    
    //Object albumIdObject = maps.get("aid");
    //Object memoObject = maps.get("memo");
    //Object monthlyCoverObject = maps.get("monthlyCover");
    //Object timelineCoverObject = maps.get("timelineCover");
    NSString *aid = [dict objectForKey:@"id"];
    
    NSArray *valueArray = [NSArray arrayWithObjects:aid, newMemo, nil];
    NSArray *keyArray = [NSArray arrayWithObjects:@"aid", @"memo", nil];
    
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    
    NSData *jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [WebRequest albumPhotoModifyWith:jsonData];
    
    CLog(@"Rqurest %@", request);
    
    [LoadingView showDefaultLoadingView];
    isMonthlyCoverModify = NO;
    
    albumModify_connection = [[WebConnectionArray  alloc] initWith:request delegate:self dataBaseListName:nil];
    
    
    
}

#pragma mark -
#pragma mark UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)modalView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // Change the navigation bar style, also make the status bar match with it
    
    NSString *str = [modalView buttonTitleAtIndex:buttonIndex];
    
    CLog(@"User sel %@, index %d", str, buttonIndex);
    
    NSInteger index = browseGallery._currentIndex;
    NSMutableDictionary *dict = [albumMonthArray objectAtIndex:index];
    
    NSData *jsonData = nil;
    
    switch (buttonIndex) {
        case 0:
        {
            NSString *aid = [dict objectForKey:@"id"];
            NSInteger photoId = [[dict objectForKey:@"photoId"] intValue];
            NSArray *valueArray = [NSArray arrayWithObjects:aid, @"1", nil];
            NSArray *keyArray = [NSArray arrayWithObjects:@"aid", @"monthlyCover", nil];
            
            NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
            
            NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
            
            jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
            
            if (jsonData != nil) {
                NSMutableURLRequest *request = [WebRequest albumPhotoModifyWith:jsonData];
                
                CLog(@"Rqurest %@", request);
                
                [LoadingView showDefaultLoadingView];
                isMonthlyCoverModify = YES;
                monthlyCoverPhotoId = photoId;
                albumModify_connection = [[WebConnectionArray  alloc] initWith:request delegate:self dataBaseListName:nil];
            }
            
            break;
        }   
        case 1:
        {
            NSString *aid = [dict objectForKey:@"id"];
            
            NSArray *valueArray = [NSArray arrayWithObjects:aid, @"1", nil];
            NSArray *keyArray = [NSArray arrayWithObjects:@"aid", @"timelineCover", nil];
            
            NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
            
            NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
            
            jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
            
            if (jsonData != nil) {
                NSMutableURLRequest *request = [WebRequest albumPhotoModifyWith:jsonData];
                
                CLog(@"Rqurest %@", request);
                
                [LoadingView showDefaultLoadingView];   
                isMonthlyCoverModify = NO;
                albumModify_connection = [[WebConnectionArray  alloc] initWith:request delegate:self dataBaseListName:nil];
            }
            
            break;
        }
        default:
        {
            return;
            break;
        }
    }
    
    
    
    
    
}


- (void)handleEditCaptionButtonTouch:(id)sender {
    // here we could implement some code to change the caption for a stored image
    
    if ([albumMonthArray count] <=0) {
        [LoadingView showDurationMessageLoadingViewWith:1.0 message:@"数据加载中，请稍等！"];
        return;
    }
    
    NSInteger index = browseGallery._currentIndex;
    
    NSMutableDictionary *dict = [albumMonthArray objectAtIndex:index];
    
    BOOL isLocale = [[dict objectForKey:@"isLocale"] boolValue];
    if (isLocale) {
        [LoadingView showDurationMessageLoadingViewWith:1.0 message:@"该图片暂时存在本地未上传，请稍后再编辑"];
        return;
    }
    else {
        [browseGallery.view addSubview:containerBgView];
        
        [textView becomeFirstResponder];
        
        NSString *memo = [dict objectForKey:@"memo"];
        memo = [[PublicMethodEngine sharedPublicMethodEngine] changeStringFommat:memo];
        if (![memo isMemberOfClass:[NSNull class]]) {
            
            textView.text = memo;
        }
        else {
            textView.text = @"";
        }    
        
        CLog(@"EditCaption ");
    }
    
    
}

- (void)moreAction:(id)sender
{
    if ([albumMonthArray count] <=0) {
        [LoadingView showDurationMessageLoadingViewWith:1.0 message:@"数据加载中，请稍等！"];
        return;
    }
    
    NSInteger index = browseGallery._currentIndex;
    
    NSMutableDictionary *dict = [albumMonthArray objectAtIndex:index];
    BOOL isLocale = [[dict objectForKey:@"isLocale"] boolValue];
    if (isLocale) {
        [LoadingView showDurationMessageLoadingViewWith:1.0 message:@"该图片暂时存在本地未上传，请稍后再编辑"];
        return;
    }
    
    UIActionSheet *inviteAlert;
    
    inviteAlert = [[UIActionSheet alloc] initWithTitle:nil
                                              delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: @"设为本月封面", @"设为宝宝主页封面", nil];
    
    
    [inviteAlert addButtonWithTitle:@"取消"];
    [inviteAlert setCancelButtonIndex:[inviteAlert numberOfButtons]-1];
    
	// use the same style as the nav bar
	inviteAlert.actionSheetStyle = (UIActionSheetStyle)self.navigationController.navigationBar.barStyle;
	
	[inviteAlert showInView:browseGallery.view];
	[inviteAlert release];
    
}


#pragma mark - FGalleryViewControllerDelegate Methods

- (NSString *)galleryPhotoCacheType
{
    
    if (localImages.count>0 ||  curIndex < localImageCount) {
        return kImageCache_Locale_Record;
    }
    else  {
        return kImageCache_Content_Browse; 
    }
    
    
}

- (int)numberOfPhotosForPhotoGallery:(FGalleryViewController *)gallery
{
    int num;
    if (localImages.count>0) {
        num = [localImages count];
    }
    else  {
        
        if (isPersonalTimeline) {
            
            if (albumMonthArray.count > 0) {
                
                 num =  [albumMonthArray count];
            }
            else{
                num = self.networkImages.count;
            }
        }
        else{
            num = [self.networkImages count];
        }
       
    }
	return num;
}


- (FGalleryPhotoSourceType)photoGallery:(FGalleryViewController *)gallery sourceTypeForPhotoAtIndex:(NSUInteger)index
{
    curIndex = index;
    
    
    if (localImages.count>0 ) {
		return FGalleryPhotoSourceTypeLocal;
	}
    else {
        return FGalleryPhotoSourceTypeNetwork;
    }
}

- (NSString *)photoGallery:(FGalleryViewController *)gallery titleForPhotoAtIndex:(NSUInteger)index
{
    
    if (isPersonalTimeline) {
        
        NSString *dateStr = nil;
        
        if( localImages.count == 0 && albumMonthArray.count >0) {
            
            NSMutableDictionary *dict = [albumMonthArray objectAtIndex:index];
            
            if (![[dict objectForKey:@"photoDate"] isMemberOfClass:[NSNull class]]) {
                dateStr = [[dict objectForKey:@"photoDate"] stringValue];
            }
        }
        
        
        if (dateStr != nil) {
            NSDate *zoneDate = [NSDate date];
            NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
            NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
            
            long long int dateTime;
            dateTime = [dateStr longLongValue];
            dateTime = dateTime/1000 +interval;
            
            NSDate *nd = [NSDate dateWithTimeIntervalSince1970:dateTime];
            NSString *createDateStr = [[PublicMethodEngine sharedPublicMethodEngine] NSDateToNSTring:nd];
            
            //int create_year = [[createDateStr substringWithRange: NSMakeRange(0, 4)] intValue];
            //int create_month=[[createDateStr substringWithRange: NSMakeRange(5, 2)] intValue];
            //int create_day=[[createDateStr substringWithRange: NSMakeRange(8, 2)] intValue];
            
            return [createDateStr substringToIndex:10];
        }
        else {
            return nil;
        }
        

    }
    
    else{
        
        NSString *titleStr ;
        
        if (localImages.count > 0) {
            
            titleStr = [NSString stringWithFormat:@"%d of %d",index+1,localImages.count];
        }
        else{
            
            titleStr = [NSString stringWithFormat:@"%d of %d",index+1,networkImages.count];
        }
     
        
        return titleStr;
    }
       
}




- (NSString*)photoGallery:(FGalleryViewController *)gallery captionForPhotoAtIndex:(NSUInteger)index
{
    curIndex = index;
    
    NSString *caption = nil;
       
    if ([albumMonthArray count]>0) {
        
        NSDictionary *dict = [albumMonthArray objectAtIndex:curIndex];
        
        NSString *memo = [dict objectForKey:@"memo"];
        if (![memo isMemberOfClass:[NSNull class]]) {
            
            memo = [[PublicMethodEngine sharedPublicMethodEngine] changeStringFommat:memo];
            
            return memo;
        }
        else {
            
            textView.text = @"";
            return @"";
        }


    }
    else{
        
        caption = @"";
    }
    
    
	return caption;
    
}


- (NSString*)photoGallery:(FGalleryViewController*)gallery filePathForPhotoSize:(FGalleryPhotoSize)size atIndex:(NSUInteger)index {
    return [localImages objectAtIndex:index];
}

- (NSString*)photoGallery:(FGalleryViewController *)gallery urlForPhotoSize:(FGalleryPhotoSize)size atIndex:(NSUInteger)index {
    
    curIndex = index;
    
    if (isPersonalTimeline && albumMonthArray.count > 0) {
        
        NSDictionary *dict = [albumMonthArray objectAtIndex:curIndex];
        
        if(![[dict objectForKey:@"photoId"] isMemberOfClass:[NSNull class]]){
            
            NSString *string=[NSString stringWithFormat:@"%@%@/%@/480x480",BASEURL,@"/commons/attachment/download",[dict objectForKey:@"photoId"]];
            
            CLog(@"Image url %@", string);
            
            return string;
        }
        else {
            
            CLog(@"Image url nil");
            return @"";
        }
        

        
    }
    else{
        
        NSString *urlForPhoto = [NSString stringWithFormat:@"%@",[imageURLArray objectAtIndex:index]];
        
        return urlForPhoto;

        
    }
    
             
      
}

//日志相片时间点后视图

- (void)loadAlbumDiary_old{
    
    if (!isLoadOld) {
        
        
        if (oldPictureCount%PageSize == 0 && minTimePoint != 0 ) { //有分页数据
            
            isLoadOld = YES;
            
            int tid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"] intValue];
            
            // NSString *_timePoint = [[albumMonthArray objectAtIndex:albumMonthArray.count-1] objectForKey:@"photoDate"];
            
            int pageNo = oldPictureCount/PageSize;
            
            if (pageNo <=0) {
                pageNo = 1;
            }
            
            NSMutableURLRequest *request = [WebRequest  albumDiaryRequestWith:tid timePoint:minTimePoint isOlder:@"true" pageNo:pageNo pageSize:PageSize];
            
            CLog(@"request %@", request);
            if (oldDiaryAlbum_connetion != nil) {
                oldDiaryAlbum_connetion.connectionDelegate = nil;
            }
            oldDiaryAlbum_connetion = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
            
        }

        
    }
    
        
   
    
}

- (void)loadAlbumDiary_new{
    
    if (!isLoadNew) {
        
        if (newPictureCount%PageSize == 0 && maxTimePoint != 0) { //有分页数据
            
            isLoadNew = YES;
            
            int tid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"] intValue];
            
            int pageNo = newPictureCount/PageSize;
            if (pageNo <=0) {
                pageNo = 1;
            }
            
            NSMutableURLRequest *request = [WebRequest  albumDiaryRequestWith:tid timePoint:maxTimePoint isOlder:@"false" pageNo:pageNo pageSize:PageSize];
            
            CLog(@"request %@", request);
            if (newDiaryAlbum_connetion != nil) {
                newDiaryAlbum_connetion.connectionDelegate = nil;
            }
            newDiaryAlbum_connetion = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
            
        }

        
    }   
    
    
       
    
    
}


//日志照片视图
- (void)loadDiaryAlbum{
    
    if (localImages.count == 0 && albumMonthArray.count == 0) {
       
        
        NSMutableString *accessList = [[NSMutableString alloc] init];
        
        for (int i = 0;i<self.networkImages.count;i++) {
            
            if (i<networkImages.count-1) {
                
                [accessList appendString:[NSString stringWithFormat:@"%@,",[networkImages objectAtIndex:i]]];
            }
            else{
                [accessList appendString:[NSString stringWithFormat:@"%@",[networkImages objectAtIndex:i]]];
            }
            
        }

      
            
        NSMutableURLRequest *request = [WebRequest diaryAlbumRequestWith:accessList];
        
        CLog(@"request %@", request);
        if (browseAlbumList_connection != nil) {
            browseAlbumList_connection.connectionDelegate = nil;
        }
        browseAlbumList_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    }
       
}

#pragma mark connectionDelegate

- (void)connectionArraySuccess:(NSDictionary *)dict  connectionURL:(NSString *)url{
    
    CLog(@"connetion success");
    
  
    
    NSRange range ;
   
    //时间点后照片
    range  = [url rangeOfString:@"isOlder=false"];
    if (range.length > 0) {
        
        isLoadNew = false;
        
          [LoadingView hideWithAnimated:NO];    
        
        if (dict) {
            
            if (albumMonthArray == nil) {
                
                albumMonthArray = [[NSMutableArray alloc] init];
            }
            
            NSArray *array = [dict objectForKey:@"object"];
            
            if (array.count > 0) {
                
                NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(0, array.count)];
                
               
                [albumMonthArray insertObjects:array atIndexes:indexes];
                
                newPictureCount += array.count;
                
                 browseGallery._currentIndex = array.count; 
                               
                [self reloadBrowseView];
            }
                     
        }
             
    }
    
    //时间点前照片
    range  = [url rangeOfString:@"isOlder=true"];
    if (range.length > 0) {
        
        isLoadOld = false;
        
        [LoadingView hideWithAnimated:NO];    
        
        if (dict) {
            
            if (albumMonthArray == nil) {
                
                albumMonthArray = [[NSMutableArray alloc] init];
            }
            
            NSArray *array = [dict objectForKey:@"object"];
            
            if (array.count > 0) {
                
                [albumMonthArray addObjectsFromArray:array];
                
                oldPictureCount += array.count;
                            
                [self reloadBrowseView];
            }
            
        }
        
    }

      
    
    //日志照片视图
    
    range  = [url rangeOfString:@"/diary/album"];
    if (range.length > 0) {
        
          [LoadingView hideWithAnimated:NO];    
        if (dict) {
            
            if (albumMonthArray == nil) {
                
                albumMonthArray = [[NSMutableArray alloc] init];
            }
            
            NSArray *array = [dict objectForKey:@"object"];
            
            if (array.count > 0) {
                
                for (NSDictionary *dict in array) {
                    NSMutableDictionary *newDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
                    
                    [albumMonthArray addObject:newDict];
                    [newDict release];
                }
                
                maxTimePoint = [[albumMonthArray objectAtIndex:0] objectForKey:@"photoDate"];
                minTimePoint = [[albumMonthArray objectAtIndex:albumMonthArray.count-1] objectForKey:@"photoDate"];
                
                [self reloadBrowseView];
            }
            
            
            
        }

        
    }
    
     range = [url rangeOfString:@"/album/photo/modify"];
    
    if (range.length >0) {
        CLog(@"Modify dict %@", dict);
        if (isMonthlyCoverModify) {
            if (![[dict objectForKey:@"object"] isMemberOfClass:[NSNull class]]) {
                if ([[dict objectForKey:@"object"] boolValue] ) {
                   
                    //月封面修改成功
                    [LoadingView showDurationMessageLoadingViewWith:5  message:@"操作成功"];
                    
                }
            }
        }
       
        
        
    }
   
    
}

- (void)connectionArrayError:(NSError *)error{
    
     [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络错误，请求失败！" duration:DEFAULT_LOADING_TIME];
    
}

- (void)connectionArrayError:(NSError *)error connectionURL:(NSString *)url{
    
    [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络错误，请求失败！" duration:DEFAULT_LOADING_TIME];
    
    NSRange range;
    range  = [url rangeOfString:@"isOlder=true"];
    if (range.length > 0) {
        
        isLoadOld = false;
        
    }
    
    
    range  = [url rangeOfString:@"isOlder=false"];
    if (range.length > 0) {
        
        isLoadNew = false;
        
    }

    
    
    
}


- (void)reloadBrowseView
{
    
    
    [browseGallery reloadGallery];
}


#pragma mark - Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
    
    
}


- (void)dealloc {
    
    [localImages release];
    
    [networkImages release];
    [imageURLArray release];
    
    [dateArray release];
    
    if (browseAlbumList_connection != nil) {
        browseAlbumList_connection.connectionDelegate = nil;
        [browseAlbumList_connection release];
        browseAlbumList_connection = nil;
    }
    
    
    if (oldDiaryAlbum_connetion != nil) {
        oldDiaryAlbum_connetion.connectionDelegate = nil;
        [oldDiaryAlbum_connetion release];
        oldDiaryAlbum_connetion = nil;
    }
    
    if (newDiaryAlbum_connetion != nil) {
        newDiaryAlbum_connetion.connectionDelegate = nil;
        [newDiaryAlbum_connetion release];
        newDiaryAlbum_connetion = nil;
    }
    
    
    [containerBgView release];
    [containerView release];
    [textView release];
    
    [super dealloc];
}


@end

